package com.example.property.viewmodel

import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.EncryptUtils
import com.example.common.vm.BaseViewModel
import com.example.property.intent.CarApplyViewIntent
import com.example.property.intent.ParkApplyViewIntent
import com.example.property.model.CarApplyRepository
import com.example.property.uistate.CarApplyUiState
import com.example.property.uistate.ParkApplyUiState
import com.google.gson.Gson
import com.tencent.mmkv.MMKV
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.toRequestBody
import javax.inject.Inject


/***/
@HiltViewModel
class ParkApplyViewModel @Inject constructor(private val repository: CarApplyRepository) :BaseViewModel<ParkApplyViewIntent>() {

    private val _uiState = MutableStateFlow<ParkApplyUiState>(ParkApplyUiState.NullState)
    val uiState :StateFlow<ParkApplyUiState> =_uiState.asStateFlow()

    override fun dispatchIntent(intent: ParkApplyViewIntent) {
        when(intent){
            is ParkApplyViewIntent.LoadParkApplyList->loadParkApplyList()
        }
    }

    private fun loadParkApplyList() {
        viewModelScope.launch (Dispatchers.IO){
            try {
                //封装参数
                var userId =MMKV.defaultMMKV().decodeInt("userId")
                var time =(System.currentTimeMillis()/1000).toString()
                var sign = EncryptUtils.encryptMD5ToString("${userId}${time}tamboo").lowercase()
                var map = mutableMapOf("userId" to userId , "time" to time ,"sign" to sign)
                val json = Gson().toJson(map)
                val body = json.toRequestBody("application/json;charset=utf-8".toMediaTypeOrNull())
                var result =repository.getParkApplyList(body)
                if (result.statuesCode=="200"){
                    _uiState.value=ParkApplyUiState.LoadParkApplySuccess(result.getValues())
                }else{
                    _uiState.value=ParkApplyUiState.LoadParkApplyFail(result.msg?:"接口加载失败: ")
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }finally {
                cancel()
            }
        }
    }
}